package java_thinking.unit_18_IO._18_9;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Desc:   想要运行一个程序，你需要向OSExecute.command()传递一个command字符串，这个命令被传递给ProcessBuilder
 *          构造器，然后产生ProcessBuilder对象被启动；
 *          未执行成功！！！
 * @author: cww
 * @DateTime: 2019-05-16 22:42
 */

public class OSExecute {
    public static void command(String command) {
        boolean err = false;
        try {
            Process process = new ProcessBuilder(command.split("-")).start();
            String s;
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((s = error.readLine()) != null) {
                System.out.println(s);
                err = true;
            }
        } catch (IOException e) {
            if (!command.startsWith("CMD /C")) {
                command("CMD-cd c:-" + command);
            } else {
                throw new RuntimeException(e);
            }
        }
        if (err) {
            throw new OSExcuteException("Error executing " + command);
        }

    }
}
